﻿using System;
using System.Reflection;

using RpcClient.Attr;
using RpcClient.Interface;
using Unity.Lifetime;

namespace RpcClient.Helper
{
    internal class UnityHelper
    {
        private static readonly Type _AttrLifetime = typeof(ClassLifetimeAttr);

        private static readonly Type _UnityInerfaceName = typeof(IUnityName);
        /// <summary>
        /// IOC标注的名称
        /// </summary>
        private static readonly Type _UnityName = typeof(UnityName);
        public static string GetUnityName(Type to)
        {
            UnityName name = (UnityName)to.GetCustomAttribute(_UnityName);
            if (name != null)
            {
                return name.Name;
            }
            else if (to.GetInterface(_UnityInerfaceName.FullName) != null)
            {
                return to.Name;
            }
            return null;
        }
        public static ITypeLifetimeManager GetLifetime(ClassLifetimeType type)
        {
            switch (type)
            {
                case ClassLifetimeType.单例:
                    return new ContainerControlledLifetimeManager();
                case ClassLifetimeType.分层:
                    return new HierarchicalLifetimeManager();
                case ClassLifetimeType.外部:
                    return new ExternallyControlledLifetimeManager();
                case ClassLifetimeType.循环引用:
                    return new PerResolveLifetimeManager();
                case ClassLifetimeType.线程:
                    return new PerThreadLifetimeManager();
                default:
                    return new TransientLifetimeManager();
            }
        }
        public static ClassLifetimeType? GetLifetimeType(Type form, Type to)
        {
            Attribute attr = to.GetCustomAttribute(_AttrLifetime);
            if (attr != null)
            {
                return ((ClassLifetimeAttr)attr).LifetimeType;
            }
            attr = form.GetCustomAttribute(_AttrLifetime);
            if (attr != null)
            {
                return ((ClassLifetimeAttr)attr).LifetimeType;
            }
            return null;
        }

    }
}
